module Blather
	class Stanza
		class Iq

			class Command < Iq
				register :command, :command, "http://jabber.org/protocol/commands"

				def self.new(type = :set)
					node = super(type)
					node.command
					node
				end

				def inherit(node)
					command.remove
					super
				end

				def command
					q = find_first('ns:command', :ns => self.class.registered_ns)
					#			q = Blather::Stanza::Iq::Command.new.inherit(q) if q
					unless q
						(self << (q = XMPPNode.new('command', self.document)))
						q.namespace = self.class.registered_ns
					end
					q
				end

				def jid
					command[:jid]
				end

				def jid=(jid)
					command[:jid] = jid
				end

				def action
					command[:action]
				end

				def action=(action)
					command[:action] = action
				end

				def node
					command[:node]
				end

				def node=(node)
					command[:node] = node
				end

				def status
					command[:status].to_sym if command[:status]
				end

				def status=(status)
					command[:status] = status
				end

				def form
					f = command.find_first('ns:x', :ns => XMPPNode::Form.registered_ns)
					f = XMPPNode.import(f) if f
					unless f
						(command << (f = XMPPNode::Form.new))
					end
					f
				end

				def submit!(hash)
					reply!
					self.id = Blather::Stanza::Iq.next_id
					
					self.type = :set
					f = self.form
					self.remove_form
					f.submit! hash
					self.command << f
				end

				def remove_form
					command.xpath("ns:x", :ns => Blather::XMPPNode::Form.registered_ns).remove
				end
				## 
				def self.import(node)
					cmd = super(node)
					#			produces infinite loop :(
					cmd = Epic::Command::Gettime.new.inherit(node) if cmd.node == 'gettime'
					cmd = Epic::Command::Execute.new.inherit(node) if cmd.node == 'execute'
					cmd
				end
			end #Command
		end #Iq
	end #Stanza
end

